package com.dd.service.impl;

import com.dd.dto.CustomRobotGroupMessage;
import com.dd.dto.OrderItemDTO;
import com.dd.entity.*;
import com.dd.mapper.PurchaseOrderDetailsMapper;
import com.dd.mapper.PurchaseOrdersMapper;
import com.dd.service.*;
import com.dd.util.OrderIdGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 采购订单表 记录采购订单信息 服务实现类
 * </p>
 *
 * @author dhd
 * @since 2024-10-21
 */
@Service
public class PurchaseOrdersServiceImpl implements IPurchaseOrdersService {
    @Autowired
    IProductsService productsService;
    @Autowired
    PurchaseOrdersMapper purchaseOrdersMapper;
    @Autowired
    PurchaseOrderDetailsMapper purchaseOrderDetailsMapper;
    @Autowired
    IPurchaseOrderDetailsService purchaseOrderDetailsService;
    @Autowired
    IPurchaseSettlementService purchaseSettlementService;
    @Autowired
    IInventoryService inventoryService;

    @Override
    @Transactional//事务
    public void createOrder(List<OrderItemDTO> orderItems) {
        //订单Id
        String orderId = "cg_" + OrderIdGenerator.generateOrderId();
        //将list转map
        Map<Integer, Integer> map = orderItems.stream().
                collect(
                        Collectors.toMap(
                                OrderItemDTO::getProductId,
                                OrderItemDTO::getQuantity)
                );
        //获取传入商品Id
        List<Integer> productIds = orderItems.stream().
                map(OrderItemDTO::getProductId).
                collect(Collectors.toList());
        //通过id获取商品集合
        List<Products> productsList = productsService.getListByIds(productIds);

        //对商品进行 按供应商进行分组
        Map<Integer, List<Products>> productBySupplierId = productsList.stream()
                .collect(Collectors.groupingBy(Products::getSupplierId));
        //遍历数据 组装结果 保存订单
        productBySupplierId.forEach((supplierId, productList) -> {
            System.out.println("供应商——" + supplierId);
            PurchaseOrders purchaseOrders = new PurchaseOrders();
            //订单编号
            purchaseOrders.setOrderId(orderId);

            //订单日期
            purchaseOrders.setOrderDate(new Date());

            //订单状态 0:未发货 1：发货中 2:已发货 3：已收货
            purchaseOrders.setStatus(0);
            //供应商Id
            purchaseOrders.setSupplierId(supplierId);
            //获取该供应商的订购商品总计
            double total = 0;
            //聚合商品项中的总价格
            // 使用Java 8的流（Stream）API计算总价
            double totalAmount = productList.stream().
                    mapToDouble(item ->
                            item.getPurchasePrice().doubleValue()
                                    * map.get(item.getProductId())).sum();
            //订单总金额
            purchaseOrders.setTotalAmount(totalAmount);
            //todo 保存到数据库
            purchaseOrdersMapper.insert(purchaseOrders);

        });


        //合成订单详情的商品项
        List<PurchaseOrderDetails> purchaseOrderDetails = productsList.stream().filter(
                item -> map.containsKey(item.getProductId())).map(
                item -> new PurchaseOrderDetails(
                        orderId,
                        item.getProductId(),
                        map.get(item.getProductId()),
                        item.getPurchasePrice().doubleValue(),
                        item.getSupplierId(),
                        map.get(item.getProductId()) * item.getPurchasePrice().doubleValue()
                )
        ).collect(Collectors.toList());
        // todo 保存订单详情
        purchaseOrderDetailsMapper.insertBatch(purchaseOrderDetails);
    }

    // 新增订单信息
    @Override
    public void insert(PurchaseOrders purchaseOrders) {
        purchaseOrdersMapper.insert(purchaseOrders);
    }

    // 分页查询
    @Override
    public PageInfo<PurchaseOrdersVO> selectAll(Integer pageNum) {
        PageHelper.startPage(pageNum,5);
        PageHelper.orderBy("order_date desc");
        List<PurchaseOrdersVO> purchaseOrders = purchaseOrdersMapper.selectList();
        purchaseOrders.forEach(item->{
            List<PurchaseOrdersVO> purchaseOrdersVOList=purchaseOrdersMapper.queryPurchaseOrders(item.getOrderId());
            item.setPurchaseOrdersVOList(purchaseOrdersVOList);
        });
        PageInfo<PurchaseOrdersVO> pageInfo = new PageInfo<>(purchaseOrders);
        return pageInfo;
    }

    @Override
    public List<PurchaseOrdersVO> queryPurchaseOrders(String orderId) {
        return purchaseOrdersMapper.queryPurchaseOrders(orderId);
    }


    @Override
    public int updateStatus(String orderId, int supplierId) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        int num = purchaseOrdersMapper.updateStatus(orderId,supplierId,1);
        //获取当前订单的全部子订单
        List<PurchaseOrdersVO> purchaseOrderVOS = purchaseOrdersMapper.queryPurchaseOrders(orderId);
        //判断订单是否全部发货
        boolean allStatusOne = purchaseOrderVOS.stream().allMatch(order -> order.getStatus() == 1);
        if(allStatusOne){
            CustomRobotGroupMessage.getSign("您有新的待收货订单");
            //将订单状态改为已发货
            return purchaseOrdersMapper.updateStatusByOrderId(orderId,2);
        }
        return num;
    }
    //修改总订单状态，也就是收货
//    收货的时候增加库存
    @Override
    public int updateStatusByOrderId(String orderId) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        List<PurchaseOrdersVO> purchaseOrderVOS = purchaseOrdersMapper.queryPurchaseOrders(orderId);
        purchaseOrderVOS.forEach(item->{
            PurchaseSettlement purchaseSettlement = new PurchaseSettlement();
            purchaseSettlement.setPoId(item.getOrderId());
            purchaseSettlement.setTotalAmount(Double.valueOf(item.getTotalAmount()));
            purchaseSettlement.setSupplierId(item.getSupplierId());
            purchaseSettlement.setShipment(new Date());
            purchaseSettlement.setSettlementStatus(0);
            purchaseSettlementService.insertInto(purchaseSettlement);
        });
        List<PurchaseOrderDetails> purchaseOrderDetails = purchaseOrderDetailsService.selectProductIdFromOrderId(orderId);
        purchaseOrderDetails.forEach(item->{
            Inventory inventory = inventoryService.selectAllByProductId(item.getProductId());
            if(inventory!=null){
                int i1 = inventoryService.updateQuantityAndCreatedTime(inventory.getQuantity() + item.getQuantity(), item.getProductId());
            }else {
                int i1 = inventoryService.insertQuantityAndCreatedTime(item.getQuantity(), item.getProductId());
            }
        });
        int i = purchaseOrdersMapper.updateStatusByOrderId(orderId, 3);
        CustomRobotGroupMessage.getSign("您有新的订单未结算");
        return 1;
    }
}

